#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
int sem_id;

void init()
{
	key_t key;

	key=ftok(".",'s');
	sem_id=semget(key,2,IPC_CREAT|0644);
	//printf("sem id is %d\n",sem_id);
}
#define produce   1 
#define customer  0
#define P   1 
#define V   0
int main(int argc,char *argv[])
{

	init();
	// 第一个信号量：食物个数
	// 第二个信号量: 盘子个数
	struct sembuf sops[2];

	
    //消费者，消费第1个信号量，p操作,食物数量-1
	sops[0].sem_num = 0;
	sops[0].sem_op = -1;
	sops[0].sem_flg = 0;

	//消费者，释放第2个信号量，v操作，盘子数量+1
	sops[1].sem_num = 1;
	sops[1].sem_op = 1;
	sops[1].sem_flg = 0;

	

	init();
	

	printf("this is customer\n");
	while(1)
	{
		printf("\n\nbefore consume:\n");
		printf("productor is %d\n",semctl(sem_id,0,GETVAL));
		printf("space  is %d\n",semctl(sem_id,1,GETVAL));
		
		semop(sem_id,&sops[0],1);		//get the productor to cusume
		printf("now consuming......\n");
		semop(sem_id,&sops[1],1);		//now tell the productor can bu produce
		
		printf("\nafter consume\n");
		printf("products number is %d\n",semctl(sem_id,0,GETVAL));
		printf("space number is %d\n",semctl(sem_id,1,GETVAL));
		sleep(2);
	}
}
